package com.ey12.file;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.util.CheckURL;
import com.alipay.util.EDcoder;
import com.ey12.utils.DateUtil;

public class PayNotify extends HttpServlet {
	private static final String CONTENT_TYPE = "text/xml; charset=utf-8";
	private static String URL = "";
	private static String USN = "";
	private static String PWD = "";

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//processRequest(request, response);
		request.getRequestDispatcher("/alipay_return.jsp").forward(request, response);	
		
		
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String partner = "2088002153549652"; //partner合作伙伴id（必须填写）
		String privateKey = "dnk9qg0mjg3n20dnmmpmtbc8fc06khdo"; //partner 的对应交易安全校验码（必须填写）
//**********************************************************************************
//如果您服务器不支持https交互，可以使用http的验证查询地址
		double total_fee=0;
	    String alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?"
				+ "&partner="
				+ partner
				+ "&notify_id="
				+ request.getParameter("notify_id");

		//获取支付宝ATN返回结果，true是正确的订单信息，false 是无效的
		String responseTxt = CheckURL.check(alipayNotifyURL);

		Map params = new HashMap();
		//获得POST 过来参数设置到新的params中
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter
				.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";				
			}
			System.out.println(name+"---"+valueStr);
			if("total_fee".equals(name)){
				total_fee=Double.valueOf(valueStr).doubleValue();
			}
			params.put(name, valueStr);
		}
		
		String mysign = com.alipay.util.SignatureHelper.sign(params, privateKey);
		
		if (mysign.equals(request.getParameter("sign")) && responseTxt.equals("true") ){
			System.out.println("success");
			processRequest(request, response,total_fee);
			PrintWriter out = response.getWriter();
			out.print("success");
			out.flush();
			out.close();
		}
		else
		{
			System.out.println("fail");
			PrintWriter out = response.getWriter();
			out.print("fail");
			out.flush();
			out.close();
		}

	}
//http://60.190.222.148/PayNotify?body=%E5%9C%B0%E4%B8%8B%E5%9F%8E%E4%B8%8E%E5%8B%87%E5%A3%AB%E6%B1%9F%E8%A5%BF2%E5%8C%BA%E9%87%91%E5%B8%81(P20090920161028)&buyer_email=wangpengpc%40126.com&buyer_id=2088002055711689&exterface=create_direct_pay_by_user&is_success=T&notify_id=RqPnCoPT3K9%252Fvwbh3I%252BJE69RHwhdhTRWeAfYv0yP87INbrKVBiTqj3L0mUaDK7%252FLLNvC&notify_time=2009-08-29+09%3A01%3A48&notify_type=trade_status_sync&out_trade_no=Sat+Aug+29+16%3A59%3A34+CST+2009&payment_type=1&seller_email=yiyouwang12%40126.com&seller_id=2088002153549652&subject=%E8%B4%AD%E4%B9%B0%E6%B8%B8%E6%88%8F%E5%B8%81&total_fee=0.01&trade_no=2009082907852693&trade_status=TRADE_FINISHED&sign=acc57a143c4865b6807e7c51c8c5d09f&sign_type=MD5
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response,double total_fee) throws ServletException, IOException {
		URL = this.getServletContext().getInitParameter("DbUrl");
		USN = this.getServletContext().getInitParameter("DbUsername");
		PWD = this.getServletContext().getInitParameter("DbPwd");

		EDcoder ed = new EDcoder();
		request.setCharacterEncoding("UTF-8");

		String sign=request.getParameter("sign");
		String trade_status=request.getParameter("trade_status");
		String is_success=request.getParameter("is_success");
		if (trade_status.equals("TRADE_FINISHED")){
//			游戏币(OS20090811094925)-游戏币(OS20090811094929) && is_success.equals("T") 
			String body=ed.of(request.getParameter("body"));
			String subject=ed.of(request.getParameter("subject"));
			System.out.println(body);
			if(body!=null){
				if(!"".equals(body)){
					String[] orderNums=body.split("-");{
					for(int i=0;i<orderNums.length;i++){
						String orderNumItem=orderNums[i];
						
						if(orderNumItem.indexOf("OS")!=-1){
							int a=orderNumItem.indexOf("OS");
							String orderNum=orderNumItem.substring(a,orderNumItem.length()-1);
							updateOrder(orderNum.trim());
							
							System.out.println(orderNumItem+"---"+a+"---"+orderNum);
							int storeId=findStoreIdByOrderNum(orderNum.trim());
							int buyNum=findBuyNumByOrderNum(orderNum.trim());
							System.out.println("findStoreIdByOrderNum--findBuyNumByOrderNum---"+storeId+"---"+buyNum);
							if(storeId!=-1&&buyNum!=-1&&buyNum>0){
								updateStore(storeId,buyNum);
							}
													
						}
						else if(orderNumItem.indexOf("P")!=-1){
							int a=orderNumItem.indexOf("P");
							String orderNum=orderNumItem.substring(a,orderNumItem.length()-1);
							System.out.println(orderNumItem+"---"+a+"---"+orderNum);							
							updateMoneyRecord(orderNum.trim());	
							findUserCountBalance(orderNum.trim(),total_fee);	
						}
					}
					}
				}
			}
			
		}
		
	}
	
	public int findBuyNumByOrderNum(String orderNum) {
		int num=-1;
		String sqlx = "select buy_num from gm_order where order_num='"+orderNum+"'";
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlx);			
			if(rs.next()) {
				num=rs.getInt("buy_num");
				System.out.println("findBuyNumByOrderNum rs="+num+"---"+ sqlx);	
				
				return num;
			}			
			System.out.println("findBuyNumByOrderNum="+num+"---"+ sqlx);			
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return num;
	}
	
//	findStoreIdByOrderNum=-1---select store_id from gm_order where order_num='OS20091023165259'
//		findBuyNumByOrderNum=-1---select buy_num from gm_order where order_num='OS20091023165259'

	public int findStoreIdByOrderNum(String orderNum) {
		int id=-1;
		
		String sqlx = "select store_id from gm_order where order_num='"+orderNum+"'";
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlx);			
			if(rs.next()) {
				id=rs.getInt("store_id");
				System.out.println("findStoreIdByOrderNum rs="+id+"---"+ sqlx);	
				rs.close();
				stmt.close();
				conn.close();
				return id;
			}			
			System.out.println("findStoreIdByOrderNum="+id+"---"+ sqlx);			
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} 
		return id;
	}
	public void updateStore(int storeId,int buyNum) {
		
		String sqlx = "update gm_game_store set store_num=store_num-"+buyNum+" where id="+storeId;
		
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
			stmt.execute(sqlx);
			System.out.println("updateStore="+sqlx);
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} 

	}
	public void updateOrder(String orderNum) {
		
		
		String sqlx = "update gm_order set pay_state=1,pay_date='"+new DateUtil().toTimeString()+"' where order_num='" + orderNum + "'";
		//update gm_order set pay_state=1,pay_date='2009-10-23 16:53:21' where order_num='OS20091023165259'
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
			stmt.execute(sqlx);
			System.out.println("updateOrder="+sqlx);
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} 

	}
	
	public void updateMoneyRecord(String orderNum) {
	
		String sqlx = "update gm_money_record set pay_state=1,state=2,pay_date='"+new DateUtil().toTimeString()+"' where order_num='" + orderNum + "'";
		
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
			stmt.execute(sqlx);
			System.out.println("updateMoneyRecord="+sqlx);
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} 

	}
	
	public void updateUserCountBalance(int user_id,double countBalance) {
		
			
		String sqlx = "update gm_user set count_balance=count_balance+"+countBalance+" where id="+user_id;
		
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
			stmt.execute(sqlx);
			stmt.close();
			conn.close();
			System.out.println("updateUserCountBalance="+sqlx);
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} 

	}
//	
//	public static void main(String[] a){
//		new PayNotify().findUserCountBalance("OS20090908043658");
//	}
	public void findUserCountBalance(String orderNum,double total_fee) {
		
		
		String sqlx = "select user_id,get_money from gm_money_record where order_num='" + orderNum + "'";
		
		try {
			Connection conn = getConnectionByJDBC();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlx);
			System.out.println("findUserCountBalance="+sqlx);
			if (rs.next()) {
				int user_id = rs.getInt("user_id");
				double get_money = rs.getDouble("get_money");
				if(total_fee==get_money){
					updateUserCountBalance(user_id,get_money);
				}else{
					updateUserCountBalance(user_id,total_fee);
				}
			}		
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} 

	}
	

	public static Connection getConnectionByJDBC() {
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection(URL, USN, PWD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

}
